#! /usr/bin/env python
#coding=utf-8
import sys, os
from uliweb.orm import get_model, set_dispatch_send, Begin, Commit, Rollback

set_dispatch_send(False)

def call(args, options, global_options):
    from uliweb.core.SimpleFrame import Dispatcher
    from uliweb.orm import Begin, Commit, Rollback

    app = Dispatcher(apps_dir=global_options.apps_dir, start=False)
    Begin()
    try:
        process(args, options, global_options)
        Commit()
    except:
        Rollback()
        import traceback
        traceback.print_exc()

def process(args, options, global_options):
    print 'Processing org_info or company_info file...'
#    if len(args) != 3:
#        print "Error, the command line is not right"
#        print "     uliweb [options] call import_department [type:ccb|company] dir"
#        return
        
    import_(args[1],  options, global_options)
        
def import_(dir, options, global_options):
    import csv
    from uliweb.orm import get_model
    

    Selfdev = get_model('selfdev')
    System = get_model('system')
    
    c_n = 0
    n_n = 0
    n = 0
        
    
    for line in csv.reader(open(dir), delimiter='|'):
        system, complexity,independent_lastyear,independent_thisyear,independent_destination,qualified_type,qualified_year = line
        system = unicode(system,'GBK')
        s = System.get(System.c.abbr==system)
        if s:
            d = Selfdev.get(Selfdev.c.system == s.id)
            if not d:
                d = Selfdev()
            d.system = s.id
            d.kfzx = s.kfzx
            d.complexity = complexity or 0.0
            d.independent_lastyear = independent_lastyear or 0.0
            d.independent_thisyear = independent_thisyear or 0.0
            d.independent_destination = independent_destination or 0.0
            d.qualified_type = qualified_type
            d.qualified_year = qualified_year
            d.save()
            c_n += 1
        else:
            print "shibai----------",system
            n_n += 1

        
        n += 1
#    os.rename(filename, os.path.join(os.path.dirname(filename), 'bak_' + os.path.basename(filename)))
    print "Total process %d, and added %d, changed %d" % (n, n_n, c_n)
